import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Space, Tag } from 'antd';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { disableUser, queryUserList, removeUser, resetPwd } from './services/user';
import UserForm from './components/UserForm';

const UserGrid = () => {
  const initState = {
    modalVisible: false,
    userRecord: {},
  };
  const [state, setState] = useState(initState);
  const actionRef = useRef();

  const handleRemove = (ids) => {
    Modal.confirm({
      title: '确认',
      icon: <QuestionCircleOutlined />,
      content: '确认删除用户？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在执行...');
        const result = await removeUser({ ids });
        hide();
        if (result.success) {
          message.success('操作成功');
          actionRef.current.clearSelected();
          actionRef.current.reload();
        } else if (result.message) {
          message.error(result.message);
        }
      },
    });
  };

  const handleDisable = async (ids, disable) => {
    const hide = message.loading('正在执行...');
    const result = await disableUser({ ids, disable });
    hide();
    if (result.success) {
      message.success('操作成功');
      actionRef.current.clearSelected();
      actionRef.current.reload();
    } else if (result.message) {
      message.error(result.message);
    }
  };

  const handleResetPass = async (ids) => {
    Modal.confirm({
      title: '确认',
      icon: <QuestionCircleOutlined />,
      content: '确认重置密码？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在执行...');
        const result = await resetPwd({ ids });
        hide();
        if (result.success) {
          const {
            data: { password },
          } = result;
          message.success(`操作成功，密码被重置为${password}`);
          actionRef.current.clearSelected();
          actionRef.current.reload();
        } else if (result.message) {
          message.error(result.message);
        }
      },
    });
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '状态',
      dataIndex: 'disabled',
      valueType: 'select',
      valueEnum: {
        true: {
          text: '禁用',
        },
        false: {
          text: '正常',
        },
      },
      render: (_, record) => {
        return record.disabled ? <Tag color="error">禁用</Tag> : <Tag color="success">正常</Tag>;
      },
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInSearch: true,
    },
    {
      title: '操作',
      width: 250,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setState({ modalVisible: true, userRecord: record });
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            handleRemove([record.id]);
          }}
        >
          删除
        </a>,
        <a
          key="disabled"
          onClick={() => {
            handleDisable([record.id], !record.disabled);
          }}
        >
          {record.disabled ? '启用' : '禁用'}
        </a>,
        <a
          key="reset"
          onClick={() => {
            handleResetPass([record.id]);
          }}
        >
          重置密码
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="用户列表"
        request={(params) => {
          const { current: pageNo, pageSize, ...rest } = params;
          return queryUserList({ pageNo, pageSize, ...rest });
        }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
        search={{
          optionRender: ({ searchText, resetText }, { form }) => {
            return [
              <Button
                key="reset"
                onClick={() => {
                  actionRef.current.clearSelected();
                  // 将查询字段清空，而不是恢复到initialValue
                  const query = form.getFieldsValue();
                  Object.keys(query).forEach((attr) => {
                    query[attr] = undefined;
                  });
                  form.setFieldsValue(query);
                  form.submit();
                }}
              >
                {resetText}
              </Button>,
              <Button
                key="search"
                type="primary"
                onClick={() => {
                  actionRef.current.clearSelected();
                  form.submit();
                }}
              >
                {searchText}
              </Button>,
            ];
          },
        }}
        toolbar={{
          actions: [
            <Button
              key="primary"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setState({ modalVisible: true, userRecord: {} });
              }}
            >
              新建用户
            </Button>,
          ],
        }}
        rowSelection={{
          columnWidth: 50,
          preserveSelectedRowKeys: true,
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={16}>
            <span>已选 {selectedRowKeys.length} 项</span>
            <span>
              <a onClick={onCleanSelected}>取消选择</a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space size={16}>
              <a
                onClick={() => {
                  handleRemove(selectedRowKeys);
                }}
              >
                批量删除
              </a>
              <a
                onClick={() => {
                  handleDisable(selectedRowKeys, true);
                }}
              >
                批量禁用
              </a>
              <a
                onClick={() => {
                  handleDisable(selectedRowKeys, false);
                }}
              >
                批量启用
              </a>
              <a
                onClick={() => {
                  handleResetPass(selectedRowKeys);
                }}
              >
                重置密码
              </a>
            </Space>
          );
        }}
      />
      {state.modalVisible && (
        <UserForm
          visible={state.modalVisible}
          onVisibleChange={(visible) => {
            setState({ ...state, modalVisible: visible });
          }}
          record={state.userRecord}
          onSuccess={() => {
            const edit = !!state.userRecord.id;
            if (edit) {
              // 编辑成功后刷新本页
              actionRef.current.clearSelected();
              actionRef.current.reload();
            } else {
              // 添加成功后跳至第一页显示添加的记录
              actionRef.current.reloadAndRest();
            }
          }}
        />
      )}
    </PageContainer>
  );
};

export default UserGrid;
